<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { timeFormat, toYuan, copyToCliboard, timeFormat_2 } from '@/hooks/util'
import * as preQuotationApi from '@/api/preQuotation'
import * as accountApi from '@/api/account'
import * as quotationRulesApi from '@/api/quotationRules'
import { message } from 'ant-design-vue'
import AddRule from './components/AddRule.vue'
import AddTemplate from '../../components/Modal/index.vue'
import addTemplateContent from './components/AddTemplate.vue'
import WeCaht from './WeCaht.vue'
import SendTemplate from './components/SendTemplate.vue'

import * as tempalteApi from '@/api/template'

const screenWidth = ref(0)
const screenHeight = ref(0)

function updateScreenSize() {
  screenWidth.value = window.innerWidth
  screenHeight.value = window.innerHeight
  console.log(screenWidth.value, screenHeight.value, 'screenWidth.value, screenHeight.value')
}
const route = useRoute()
const router = useRouter()

const sendTemplateRef = ref()
const addRuleRef = ref()
const AddTemplateRef = ref()
const WeCahtRef = ref()

interface Pagination {
  page: number
  pageSize: number
  total: number
  current?: number
  onChange: Function
  showSizeChanger: boolean
}

const handlePageChange = (page: any, pageSize: any) => {
  pagination.value.pageSize = pageSize
  searchParams.value.pageSize = pageSize
}

const pagination = ref<Pagination>({
  page: 1,
  pageSize: 10,
  total: 0,
  onChange: handlePageChange,
  showSizeChanger: true,
})
let loading = ref<boolean>(false)

interface SearchParams {
  currentPage: number
  pageSize: number
  channel: number
  [propName: string]: any
}
const searchParams = ref<SearchParams>({
  channel: 3, // 闲鱼
  currentPage: pagination.value.page,
  pageSize: pagination.value.pageSize,
})

const dataSource = ref([])
const columns = [
  {
    title: '名称/院线',
    key: 'name',
    width: 400,
  },
  {
    title: '排除影院/规则权重',
    key: 'cinemaList',
    width: 400,
  },
  {
    title: '报价出票模式',
    key: 'ticketMode',
    width: 200,
  },
  // {
  //   title: '首选渠道/备选渠道',
  //   key: 'matchChannel',
  //   width: 180,
  // },
  {
    title: '报价调整类型/报价方式',
    key: 'finalPriceAdjustType',
    width: 400,
  },
  // {
  //   title: '报价方式',
  //   key: 'quotationType',
  //   width: 120,
  // },
  {
    title: '报价金额/是否限价',
    key: 'quotationAmount',
    width: 400,
  },
  // {
  //   title: '是否限价',
  //   key: 'enableLimitPrice',
  //   width: 120,
  // },
  {
    title: '启用状态',
    key: 'status',
    width: 400,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
    align: 'center',
  },
]

// 翻页
const changePage = (e: any) => {
  pagination.value.current = e.current
  pagination.value.pageSize = e.pageSize
  searchParams.value.currentPage = pagination.value.current as number
  getList()
}

const getList = async () => {
  loading.value = true
  try {
    let {
      state,
      data,
      message: msg,
    } = await preQuotationApi.getSimpleQuotationList(searchParams.value)
    if (state === 200) {
      dataSource.value = data.list.map((item: any) => {
        item.statusFlag = item.status === 1
        return item
      })
      pagination.value.total = Number(data.totalCount)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}

import type { SelectProps } from 'ant-design-vue'
const orderStatusList = ref<SelectProps['options']>([
  {
    label: '禁用',
    value: 0,
  },
  {
    label: '启用',
    value: 1,
  },
])
//渠道下拉框
const changeTicketChannel = (e: any) => {
  if (!e) {
    delete searchParams.value.ticketChannel
  }
}
const ticketChannelList = ref<SelectProps['options']>([
  {
    label: '麻花电影票',
    value: 3,
  },
  {
    label: '守兔电影票',
    value: 11,
  },
  {
    label: '守兔',
    value: 7,
  },
  {
    label: '芒果电影票',
    value: 5,
  },
  {
    label: '哈哈电影快票',
    value: 9,
  },
  {
    label: '星驰电影票',
    value: 8,
  },
  {
    label: '影划算电影票',
    value: 10,
  },
])

const formRef = ref()
interface FormState {
  name?: string
  status?: number
  ticketChannel?: number
  [propName: string]: any
}
const formState = reactive<FormState>({})

// 查询
const search = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.validate().then(() => {
    searchParams.value.name = formState.name || ''

    if (formState.name != '') {
      searchParams.value.name = formState.name
    }

    if (formState.ticketChannel) {
      searchParams.value.ticketChannel = formState.ticketChannel
    }

    if (formState.status == 0 || formState.status == 1) {
      searchParams.value.status = formState.status
    }
    getList()
  })
}

// 重置
const reset = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.resetFields()
  for (let key in searchParams.value) {
    if (key != 'currentPage' && key != 'pageSize' && key != 'channel' && key != 'robotId')
      searchParams.value.hasOwnProperty(key) && delete searchParams.value[key]
  }
  getList()
}

// 新增规则
const add = () => {
  addRuleRef.value.showModal(3, okRobat.value)
}

// 编辑规则
const edit = (record: Object) => {
  addRuleRef.value.showModal(3, okRobat.value, record)
}

const activeKey = ref<string>('1')

onMounted(() => {
  getRobatList()
  getGroupList()
  updateScreenSize()
})

// 拉取机器人列表
let okRobat = ref<string>()
const robatList = ref<SelectProps['options']>([])

interface OptionList {
  label: string
  value: string
}
let optionList = ref<Array<OptionList>>([])
const getRobatList = async () => {
  const params = {
    currentPage: 1,
    pageSize: 100,
  }
  try {
    let { state, data, message: msg } = await accountApi.getFishRobotList(params)
    if (state === 200) {
      robatList.value = data.list
      optionList.value = data.list.map((item: any) => {
        return {
          label: item.nickName,
          value: item.id,
        }
      })

      optionsArr.value = data.list
      if (data.list.length == 0) {
        message.error('闲鱼：无平台账号，请先添加平台账号')
      } else if (data.list.length > 0) {
        selectRobat(data.list[0].id)
      }
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
const selectRobat = (selectValue: unknown) => {
  okRobat.value = selectValue as string
  searchParams.value.robotId = okRobat.value
  getList()
}

// 推送
const groupList = ref<SelectProps['options']>([])
const groupId = ref<string>()
const optionsArr = ref<SelectProps['options']>([])
const getGroupList = async () => {
  try {
    let { state, data, message: msg } = await accountApi.getFishRobotGroupList()
    if (state === 200) {
      groupList.value = data
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
const selectGroup = (selectValue: any) => {
  groupId.value = selectValue as string
  sendRobat.value = optionsArr
    .value!.filter(item => item.groupId == groupId.value)
    .map(item => item.id)
}

// 推送配置
let sendRobat = ref<Array<string>>()
const selectSendRobat = (selectValue: any) => {
  sendRobat.value = selectValue
}
const pushRobot = async () => {
  // console.log('okRobat=', okRobat.value)
  // console.log('sendRobat=', sendRobat.value)
  let params = {
    acceptRobotIds: sendRobat.value,
    channel: 3,
    sendRobotId: okRobat.value,
  }
  try {
    const { state, message: msg } = await preQuotationApi.simpleQuotationPushRobots(params)
    if (state === 200) {
      message.success('操作成功')
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
const sendOk = () => pushRobot()

// select搜索
const filterOption = (input: string, option: any) => {
  return option.label.indexOf(input) >= 0
}

// 删除
const del = async (id: string) => {
  try {
    const { state, message: msg } = await preQuotationApi.deleteSimpleQuotation({ id })
    if (state === 200) {
      message.success('删除成功')
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

const handleChangeRules = async (record: any) => {
  try {
    const { state, message: msg } = await preQuotationApi.editSimpleQuotationStatus({
      id: record.id,
      status: record.status ? 0 : 1,
    })
    if (state === 200) {
      message.success('操作成功')
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 简易预报价
const preQuotation = () => {
  router.push({ path: '/pre-quotation' })
}

// 获取 模板id
let TemplateId = ref('')
const getTHEID = id => {
  console.log('id=', id)
  TemplateId.value = id
}

// 弹框确定
const handleConfirm = async () => {
  // AddTemplateRef.value.setVisible(false)

  console.log('okRobat=====', okRobat.value)
  console.log('TemplateId=====', TemplateId.value)

  try {
    const { state, message: msg } = await tempalteApi.installGroupSimpleQuotation({
      groupId: TemplateId.value,
      robotId: okRobat.value,
    })
    if (state === 200) {
      message.success('操作成功')
      AddTemplateRef.value.setVisible(false)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
</script>

<template>
  <page-container :title="route.meta.title">
    <a-card style="overflow-x: scroll">
      <a-tabs v-model:activeKey="activeKey">
        <a-tab-pane key="1" tab="闲鱼">
          <div style="margin: 5px 0; text-align: right">
            <span>选择闲鱼账号：</span>
            <a-select
              v-model:value="okRobat"
              @change="selectRobat"
              placeholder="请选择"
              style="width: 200px; text-align: left"
              show-search
              :options="optionList"
              :filter-option="filterOption"
            >
              <a-select-option v-for="(item, index) in optionList" :key="index" :value="item.value">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </div>
          <div class="searchBox">
            <a-form ref="formRef" layout="inline" :model="formState">
              <a-form-item label="名称" name="name">
                <a-input v-model:value="formState.name" placeholder="名称" style="width: 200px" />
              </a-form-item>

              <a-form-item label="状态" name="status">
                <a-select
                  v-model:value="formState.status"
                  placeholder="状态"
                  style="width: 200px"
                  allowClear
                >
                  <a-select-option
                    v-for="(item, index) in orderStatusList"
                    :key="index"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>

              <!-- <a-form-item label="询价渠道" name="ticketChannel">
                <a-select
                  v-model:value="formState.ticketChannel"
                  placeholder="询价渠道"
                  style="width: 200px"
                  allowClear
                  @change="changeTicketChannel"
                >
                  <a-select-option
                    v-for="(item, index) in ticketChannelList"
                    :key="index"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item> -->

              <a-form-item>
                <a-button type="primary" @click="search">搜索</a-button>
                <a-button @click="reset">重置</a-button>
                <a-button type="primary" @click="add">新增规则</a-button>
                <a-button type="primary" @click="sendTemplateRef.showModal()">模板列表</a-button>
              </a-form-item>
            </a-form>
          </div>

          <a-alert
            description="小提示：只要鼠标在表格上，按住左Shift键并滚动鼠标滚轮就可以横向滚动表格"
            type="info"
            banner
            style="margin-bottom: 10px; padding: 10px"
          />

          <a-table
            style="overflow-x: scroll"
            :columns="columns"
            :data-source="dataSource"
            :pagination="pagination"
            :loading="loading"
            @change="changePage"
            rowKey="id"
            :scroll="{ x: 100 }"
          >
            <template #emptyText>
              <a-empty description="暂无数据" />
            </template>

            <template #headerCell="{ column }"></template>

            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'name'">
                <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
                  <a-descriptions-item label="规则名称">
                    <a-tooltip placement="top">
                      <template #title>
                        <span>{{ record.name }}</span>
                      </template>
                      <span class="hiddenText">{{ record.name }}</span>
                    </a-tooltip>
                  </a-descriptions-item>
                  <a-descriptions-item label="院线">
                    <a-tooltip placement="top">
                      <template #title>
                        <a-tag color="blue" v-for="item in record.lineList" :key="item">
                          {{ item.lineName }}
                        </a-tag>
                      </template>
                      <div class="hiddenText">
                        <a-tag
                          style="line-height: 16px"
                          color="blue"
                          v-for="item in record.lineList"
                          :key="item"
                        >
                          {{ item.lineName }}
                        </a-tag>
                      </div>
                    </a-tooltip>
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-if="column.key === 'cinemaList'">
                <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
                  <a-descriptions-item label="排除影院">
                    <a-tooltip placement="top">
                      <template #title>
                        <a-tag color="blue" v-for="item in record.cinemaList" :key="item">
                          {{ item.name }}
                        </a-tag>
                      </template>
                      <div class="hiddenText">
                        <a-tag
                          style="line-height: 16px"
                          color="blue"
                          v-for="item in record.cinemaList"
                          :key="item"
                        >
                          {{ item.name }}
                        </a-tag>
                      </div>
                    </a-tooltip>
                  </a-descriptions-item>
                  <a-descriptions-item label="规则权重">
                    {{ record.sort || 0 }}
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-if="column.key === 'ticketMode'">
                <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
                  <a-descriptions-item label="报价出票模式">
                    <a-tag color="blue" v-if="record.quotationMode == 2">一口价</a-tag>
                    <a-tag color="blue" v-if="record.quotationMode == 1">预估限价</a-tag>
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-else-if="column.key === 'ticketChannel'">
                <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
                  <a-descriptions-item label="询价渠道">
                    <a-tag color="blue" v-if="record.ticketChannel == 3">麻花电影票</a-tag>
                    <a-tag color="blue" v-if="record.ticketChannel == 11">守兔电影票</a-tag>
                    <a-tag color="blue" v-if="record.ticketChannel == 7">守兔</a-tag>
                    <a-tag color="blue" v-if="record.ticketChannel == 6">哈哈电影票</a-tag>
                    <a-tag color="blue" v-if="record.ticketChannel == 5">芒果电影票</a-tag>
                    <a-tag color="blue" v-if="record.ticketChannel == 9">哈哈电影快票</a-tag>
                    <a-tag color="blue" v-if="record.ticketChannel == 8">星驰电影票</a-tag>
                    <a-tag color="blue" v-if="record.ticketChannel == 10">影划算电影票</a-tag>
                    <a-tag color="blue" v-if="record.ticketChannel == 99">动态渠道</a-tag>
                  </a-descriptions-item>
                  <a-descriptions-item label="供应渠道">
                    <a-tag color="blue" v-if="record.matchChannel == 3">麻花电影票（可限价）</a-tag>
                    <a-tag color="blue" v-if="record.matchChannel == 11">
                      守兔电影票（一口价）
                    </a-tag>
                    <a-tag color="blue" v-if="record.matchChannel == 7">守兔电影票（可限价）</a-tag>
                    <a-tag color="blue" v-if="record.matchChannel == 5">芒果电影票（一口价）</a-tag>
                    <a-tag color="blue" v-if="record.matchChannel == 6">哈哈电影票</a-tag>
                    <a-tag color="blue" v-if="record.matchChannel == 9">
                      哈哈电影快票（固定9折）
                    </a-tag>
                    <a-tag color="blue" v-if="record.matchChannel == 8">星驰电影票（一口价）</a-tag>
                    <a-tag color="blue" v-if="record.matchChannel == 99">动态渠道</a-tag>
                    <a-tag color="blue" v-if="record.matchChannel == 10">
                      影划算电影票（可限价）
                    </a-tag>

                    <a-tag color="blue" v-if="record.slaveMatchChannel == 3">
                      麻花电影票（可限价）
                    </a-tag>
                    <a-tag color="blue" v-if="record.slaveMatchChannel == 6">哈哈电影票</a-tag>
                    <a-tag color="blue" v-if="record.slaveMatchChannel == 11">
                      守兔电影票（一口价）
                    </a-tag>
                    <a-tag color="blue" v-if="record.slaveMatchChannel == 7">
                      守兔电影票（可限价）
                    </a-tag>
                    <a-tag color="blue" v-if="record.slaveMatchChannel == 5">
                      芒果电影票（一口价）
                    </a-tag>
                    <a-tag color="blue" v-if="record.slaveMatchChannel == 9">
                      哈哈电影快票（固定9折）
                    </a-tag>
                    <a-tag color="blue" v-if="record.slaveMatchChannel == 8">
                      星驰电影票（一口价）
                    </a-tag>
                    <a-tag color="blue" v-if="record.slaveMatchChannel == 10">
                      影划算电影票（可限价）
                    </a-tag>
                    <a-tag color="blue" v-if="record.slaveMatchChannel == 0">不使用</a-tag>
                    <a-tag color="blue" v-if="record.slaveMatchChannel == 99">动态渠道</a-tag>
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-else-if="column.key === 'finalPriceAdjustType'">
                <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '140px' }">
                  <a-descriptions-item label="报价调整类型">
                    <span v-if="record.finalPriceAdjustType == 1">四舍五入到整数元</span>
                    <span v-if="record.finalPriceAdjustType == 2">四舍五入到元-0.1</span>
                    <span v-if="record.finalPriceAdjustType == 3">到0.5/整数元</span>
                    <span v-if="record.finalPriceAdjustType == 0">不调整</span>
                  </a-descriptions-item>
                  <a-descriptions-item label="报价方式">
                    <span v-if="record.quotationType == 1">加法</span>
                    <span v-if="record.quotationType == 2">减法</span>
                    <span v-if="record.quotationType == 3">比例（百分比加法）</span>
                    <span v-if="record.quotationType == 4">比例（百分比减法）</span>
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-else-if="column.key === 'quotationAmount'">
                <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '120px' }">
                  <a-descriptions-item label="报价金额">
                    <span v-if="record.quotationType == 1">
                      预估成本
                      <span style="color: red">+</span>
                      {{ Math.abs(toYuan(record.discount) as any) }} ￥
                    </span>
                    <span v-if="record.quotationType == 2">
                      预估成本
                      <span style="color: red">-</span>
                      {{ Math.abs(toYuan(record.discount) as any) }} ￥
                    </span>
                    <span v-if="record.quotationType == 3">
                      预估成本
                      <span style="color: red">*</span>
                      (1 + {{ record.percent }}%)
                    </span>
                    <span v-if="record.quotationType == 4">
                      预估成本
                      <span style="color: red">*</span>
                      (1 {{ record.percent }}%)
                    </span>
                  </a-descriptions-item>
                  <a-descriptions-item label="是否限价">
                    <div v-if="record.quotationMode == 1">
                      <a-tag color="blue" v-if="record.enableLimitPrice == 1">启用</a-tag>
                      <a-tag color="red" v-if="record.enableLimitPrice == 0">不启用</a-tag>
                    </div>
                    <div v-else>无需设置</div>
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-else-if="column.key === 'status'">
                <!-- <a-tag color="red" v-if="record.status == 0">禁用</a-tag>
                <a-tag color="blue" v-if="record.status == 1">启用</a-tag> -->
                <!-- <a-switch v-model:checked="record.statusFlag" @change="handleChangeRules(record)" /> -->

                <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '120px' }">
                  <a-descriptions-item label="启用状态">
                    <a-switch
                      v-model:checked="record.statusFlag"
                      @change="handleChangeRules(record)"
                    />
                  </a-descriptions-item>
                  <a-descriptions-item label="单张限价">
                    <div v-if="record.quotationMode == 1">
                      <div v-if="record.limitPrice >= 0">
                        【报价】 + {{ record.limitPrice / 100 }}
                      </div>
                      <div v-if="record.limitPrice < 0">
                        【报价】 - {{ (0 - record.limitPrice) / 100 }}
                      </div>
                    </div>
                    <div v-else>无需设置</div>
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-else-if="column.key === 'action'">
                <a-space>
                  <a @click="edit(record)">编辑</a>
                  <a-popconfirm
                    title="确定删除？"
                    ok-text="是"
                    cancel-text="否"
                    @confirm="del(record.id)"
                  >
                    <a>删除</a>
                  </a-popconfirm>
                </a-space>
              </template>
            </template>
          </a-table>
          <!-- 推送 -->
          <div style="margin: 5px 0">
            <span>选择推送闲鱼账号：</span>
            <a-select
              style="width: 150px"
              placeholder="请选择分组"
              v-model:value="groupId"
              @change="selectGroup"
            >
              <a-select-option v-for="(item, index) in groupList" :key="index" :value="item.id">
                {{ item.groupName }}
              </a-select-option>
            </a-select>
            <a-select
              style="width: 50%; margin-left: 5px"
              placeholder="请选择"
              mode="multiple"
              v-model:value="sendRobat"
              @change="selectSendRobat"
              allowClear
              show-search
              :options="optionList"
              :filter-option="filterOption"
            >
              <a-select-option v-for="(item, index) in optionList" :key="index" :value="item.value">
                {{ item.label }}
              </a-select-option>
            </a-select>
            <a-button type="primary" style="margin: 0 10px" @click="sendOk">确认推送</a-button>
            <a-button type="primary" @click="AddTemplateRef.setVisible(true)">设置为模板</a-button>
          </div>
        </a-tab-pane>
        <a-tab-pane key="2" tab="微信" force-render>
          <WeCaht ref="WeCahtRef"></WeCaht>
        </a-tab-pane>
      </a-tabs>
    </a-card>

    <AddRule ref="addRuleRef" @refresh="getList"></AddRule>

    <AddTemplate
      :width="800"
      :height="800"
      title="请选择勾选单个模板进行保存"
      ref="AddTemplateRef"
      @onConfirmAdd="handleConfirm"
    >
      <template #contentValue>
        <addTemplateContent
          @sendTheID="getTHEID"
          :screenWidth="screenWidth"
          :screenHeight="screenHeight"
          :type="3"
        ></addTemplateContent>
      </template>
    </AddTemplate>

    <SendTemplate ref="sendTemplateRef"></SendTemplate>
  </page-container>
</template>

<style lang="less" scoped>
.hiddenText {
  display: inline-block;
  max-width: 140px;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  line-height: 16px;
}

.searchBox {
  margin-bottom: 10px;
  display: flex;

  input {
    width: 200px;
    margin-right: 10px;
  }

  button {
    margin-right: 10px;
  }
}

a:hover {
  color: red;
}
</style>
